import { ref, onMounted, onUnmounted } from 'vue';

export default function usePlayer(id: string) {
  const player = ref<any>(null);
  const currentWindowIndex = ref(0);
  const splitNum = ref(1);
  const playbackRate = ref(0);
  const mseSupport = ref(!!window.MediaSource);
  const mode = computed(() => (mseSupport.value ? 0 : 1));
  const isFull = ref(false);
  const createPlayer = () => {
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-expect-error
    player.value = new JSPlugin({
      szId: id,
      szBasePath: './',
      iMaxSplit: 1,
      iCurrentSplit: 2,
      openDebug: true,
      oStyle: {
        borderSelect: '#FFCC00'
      }
    });
    // Setup callbacks
    player.value.JS_SetWindowControlCallback({
      windowEventSelect: (iWndIndex: number) => {
        console.log('windowSelect callback: ', iWndIndex);
      },
      pluginErrorHandler: (iWndIndex: number, iErrorCode: number, oError: any) => {
        console.log('pluginError callback: ', iWndIndex, iErrorCode, oError);
      },
      windowFullCcreenChange: (bFull: boolean) => {
        console.log('fullScreen callback: ', bFull);
        isFull.value = bFull;
      },
      firstFrameDisplay: (iWndIndex: number, iWidth: number, iHeight: number) => {
        console.log('firstFrame loaded callback: ', iWndIndex, iWidth, iHeight);
      },
      performanceLack: () => {
        console.log('performanceLack callback: ');
      }
    });
  };

  const arrangeWindow = () => {
    player.value.JS_ArrangeWindow(splitNum.value).then(
      () => {
        console.log(`arrangeWindow to ${splitNum.value}x${splitNum.value} success`);
      },
      (e: any) => {
        console.error(e);
      }
    );
  };

  const realplay = (url: string) => {
    return player.value.JS_Play(url, { playURL: url, mode: mode.value }, currentWindowIndex.value);
  };

  const stopPlay = () => {
    return player.value.JS_Stop().then(() => {
      playbackRate.value = 0;
    });
  };

  onMounted(() => {
    createPlayer();
    arrangeWindow();
    window.addEventListener('resize', () => {
      player.value?.JS_Resize();
    });
  });

  onUnmounted(() => {
    window.removeEventListener('resize', () => {
      player.value?.JS_Resize();
    });
  });

  return {
    player,
    currentWindowIndex,
    splitNum,
    playbackRate,
    mseSupport,
    mode,
    isFull,
    createPlayer,
    arrangeWindow,
    realplay,
    stopPlay
  };
}
